﻿using System;
using System.Collections.Generic;
using NHibernate;

namespace SevenDigital.EndUserManagement.Core.Repository
{
	//CC: Should I be passing in IUnitOfWork implementation?
	public abstract class BaseRepository<TEntity, TIdentity> :
		IRepository<TEntity, TIdentity>
		where TEntity: IEntity<TIdentity>
		where TIdentity: struct
	{
		private readonly ISessionFactory _sessionFactory;
		private readonly ISession _session;

		public BaseRepository(ISessionFactory sessionFactory) {
			_sessionFactory = sessionFactory;
			_session = sessionFactory.OpenSession();
		}

	

		public ISession Session {
			get { return _session; }
		}

		public TEntity FindById(TIdentity id) {
			return Session.Load<TEntity>(id);
		}

		public TEntity FindByIdAndLock(TIdentity id) {
			throw new NotImplementedException();
		}

		public IList<TEntity> FindAll() {
			return Session.CreateCriteria(typeof (TEntity)).List<TEntity>();
		}

		public TEntity MakePersistent(TEntity entity) {
			Session.SaveOrUpdate(entity);
			return entity;
		}

		public void MakeTransient(TEntity entity) {
			Session.Delete(entity);
		}
	}
}